/*
 * @Author: bor_fish 1219854025@qq.com
 * @Date: 2025-04-22 18:05:19
 * @LastEditors: bor_fish 1219854025@qq.com
 * @LastEditTime: 2025-05-15 15:33:35
 * @FilePath: /myCAN/Summarizer.cpp
*/
#include "Summarizer.h"
#include <iostream>
#include <iomanip>
#include <chrono>
void Summarizer::summarizeLoop() {
    std::cout << "Summary thread started!" << std::endl;
    while(running) {
        // 获取当前时间
        auto start_time = std::chrono::steady_clock::now();
        
        // 收集统计信息
        {
            std::lock_guard<std::mutex> lock(stats_mutex_);
            
            // 重置统计信息
            stats_.total_packets = 0;
            stats_.processed_packets = 0;
            stats_.buffer_usage = 0;
            
            // 遍历所有诊断线程
            for(auto diagnostic : diagnostics) {
                // 获取CanListener的引用
                CanListener& listener = diagnostic->getListener();
                
                // 遍历所有CAN接口
                for(size_t i = 0; i < listener.getCanSize(); ++i) {
                    // 获取当前写入索引
                    int current_write_index = listener.getWriteIndex(i);
                    
                    // 计算缓冲区使用率
                    stats_.buffer_usage = (current_write_index % listener.getBufferSize()) * 100 / listener.getBufferSize();
                    
                    // 统计总包数
                    stats_.total_packets += current_write_index;
                    
                    // 统计已处理包数
                    stats_.processed_packets += listener.getProcessedCount();
                }
            }
            
            // 打印统计信息
            // std::cout << "\n=== Buffer Statistics ===" << std::endl;
            // std::cout << "Total packets: " << stats_.total_packets << std::endl;
            // std::cout << "Processed packets: " << stats_.processed_packets << std::endl;
            // std::cout << "Buffer usage: " << stats_.buffer_usage << "%" << std::endl;
            // std::cout << "=====================" << std::endl;
        }
        
        // 等待到下一个5秒间隔
        auto end_time = std::chrono::steady_clock::now();
        auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
        auto sleep_time = std::chrono::milliseconds(5000) - elapsed;
        
        if(sleep_time.count() > 0) {
            std::this_thread::sleep_for(sleep_time);
        }
    }
    
    std::cout << "Summary thread stopped!" << std::endl;
}
